<template>
  <div class="upload-container">
    <el-button
      icon="el-icon-upload"
      size="mini"
      :style="{ background: color, borderColor: color }"
      @click="dialogVisible = true"
      type="primary"
      >上传图片
    </el-button>
    <el-dialog append-to-body :visible.sync="dialogVisible">
      <el-upload
        class="editor-slide-upload"
        action
        :http-request="Upload"
        :data="dataObj"
        :multiple="true"
        :file-list="fileList"
        :show-file-list="true"
        list-type="picture-card"
        :on-remove="handleRemove"
        :on-success="handleSuccess"
        :before-upload="beforeUpload"
        :limit="1"
      >
        <el-button size="small" type="primary">点击上传</el-button>
      </el-upload>
      <el-progress
        v-show="showProgress"
        :text-inside="true"
        :stroke-width="15"
        :percentage="progress"
      ></el-progress>
      <div style="margin-top: 16px">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleSubmit">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
// import { policy, getFileNameUUID } from "@/api/oss";
// import { client , getFileNameUUID  } from "@/api/ali-oss"; //前面的ali-js文件内的两个封装函数

export default {
  name: "editorSlideUpload",
  props: {
    color: {
      type: String,
      default: "#1890ff",
    },
  },
  data() {
    return {
      showProgress: false,
      progress: 0, //进度条数据
      dialogVisible: false,
      listObj: {},
      fileList: [],
      dataObj: {
        policy: "",
        signature: "",
        key: "",
        ossaccessKeyId: "",
        dir: "",
        host: "",
      },
    };
  },
  methods: {
    checkAllSuccess() {
      console.log(this.listObj);
      return Object.keys(this.listObj).every((item) => this.listObj[item].hasSuccess);
    },
    handleSubmit() {
      const arr = Object.keys(this.listObj).map((v) => this.listObj[v]);
      if (!this.checkAllSuccess()) {
        this.$message("请等待所有图片上传成功 或 出现了网络问题，请刷新页面重新上传！");
        return;
      }
      console.log(arr);
      this.$emit("successCBK", arr);
      this.listObj = {};
      this.fileList = [];
      this.dialogVisible = false;
    },
    handleSuccess(res, fileName, uid) {
      const objKeyArr = Object.keys(this.listObj);
      for (let i = 0, len = objKeyArr.length; i < len; i++) {
        if (this.listObj[objKeyArr[i]].uid === uid) {
          this.listObj[objKeyArr[i]].url = res;
          this.listObj[objKeyArr[i]].hasSuccess = true;
          return;
        }
      }
    },
    handleRemove(file) {
      const uid = file.uid;
      const objKeyArr = Object.keys(this.listObj);
      for (let i = 0, len = objKeyArr.length; i < len; i++) {
        if (this.listObj[objKeyArr[i]].uid === uid) {
          delete this.listObj[objKeyArr[i]];
          return;
        }
      }
    },
    Upload(file) {
      console.log(file);
      const that = this;
      // 定义上传方法。
      async function multipartUpload() {
        try {
          const params = new FormData(); // 声明formData数据类型
          params.append("file", file.file);
          let fileName = getFileNameUUID() + "." + file.file.name;
          that.listObj[fileName] = {};
          that.listObj[fileName] = {
            hasSuccess: false,
            uid: file.file.uid,
            width: "100%",
          };
          // console.log(fileName);
          // console.log(file);

          policy(params)
            .then((res) => {
              console.log("Upload - policy", res);
              that.handleSuccess(res, fileName, file.file.uid);
            })

            .catch((err) => {
              // debugger;
              console.log("err:", err);
            });
          // client(that.dataObj)
          //   .multipartUpload(`${that.dataObj.dir}/${fileName}`, file.file, {
          //     progress: function (p) {
          //       //p进度条的值
          //       // console.log(p);
          //       that.showProgress = true;
          //       that.progress = Math.floor(p * 100);
          //     },
          //   })
          //   .then((result) => {
          //     // // debugger
          //     //上传成功返回值，可针对项目需求写其他逻辑
          //     // console.log(result);
          //     that.dataObj.fileName = result.name;
          //     that.handleSuccess(result, fileName, file.file.uid);
          //   })
          //   .catch((err) => {
          //     // debugger;
          //     console.log("err:", err);
          //   });
        } catch (e) {
          console.log(e);
        }
      }
      // 开始分片上传。
      multipartUpload();
    },
    beforeUpload(file) {
      return true;
    },
  },
};
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
.upload-container .editor-slide-upload {
  margin-bottom: 20px;
}
</style>
